package com.atguigu.system.controller;


import com.atguigu.admin.model.entity.SysUser;
import com.atguigu.admin.service.SysUserService;
import com.atguigu.admin.utils.DataUtil;
import com.atguigu.common.result.Result;
import com.atguigu.common.utils.JwtUtils;
import com.atguigu.system.model.entity.InventoryFlow;
import com.atguigu.system.model.entity.InventoryInfo;
import com.atguigu.system.service.InventoryFlowService;
import com.atguigu.system.service.InventoryInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 
 * @since 2025-03-01
 */
@RestController
@RequestMapping("/system/inventory-info")
public class InventoryInfoController {

    @Autowired
    private InventoryInfoService inventoryInfoService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private InventoryFlowService inventoryFlowService;

    // 新增库存信息
    @PostMapping("/save")
    public Result<?> saveInventoryInfo(@RequestBody InventoryInfo inventoryInfo, HttpServletRequest request) {

        Integer skuId = inventoryInfo.getSkuId();
        LambdaQueryWrapper<InventoryInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(InventoryInfo::getSkuId, skuId);
        List<InventoryInfo> list = inventoryInfoService.list(queryWrapper);
        if (DataUtil.isNotEmpty(list)){
            return Result.fail("该商品库存信息已存在！");
        }
        boolean save = inventoryInfoService.save(inventoryInfo);
        extracted(inventoryInfo, request);
        if (save) {
            return Result.ok();
        } else {
            return Result.fail("新增库存信息失败");
        }
    }

    private void extracted(InventoryInfo inventoryInfo, HttpServletRequest request) {
        // 对入库信息添加新增记录
        String userId = JwtUtils.getUserId(request.getHeader("token"));
        SysUser byId = sysUserService.getById(userId);

        InventoryFlow inventoryFlow = new InventoryFlow();
        // 操作人ID
        inventoryFlow.setOperatorId(Math.toIntExact(byId.getId()));
        // 操作人名字
        inventoryFlow.setOperatorName(byId.getName());
        // 修改数量
        inventoryFlow.setChangeQuantity(inventoryInfo.getCurrentStock());
        // 库存ID
        inventoryFlow.setInventoryId(inventoryInfo.getInventoryId());

        inventoryFlow.setOperationType("入库");
        // 操作原因
        inventoryFlow.setOperationReason(inventoryInfo.getReason());
        inventoryFlowService.getBaseMapper().insert(inventoryFlow);
    }

    private void extracted1(InventoryInfo inventoryInfo, HttpServletRequest request) {
        // 对入库信息添加新增记录
        String userId = JwtUtils.getUserId(request.getHeader("token"));
        SysUser byId = sysUserService.getById(userId);

        InventoryFlow inventoryFlow = new InventoryFlow();
        // 操作人ID
        inventoryFlow.setOperatorId(Math.toIntExact(byId.getId()));
        // 操作人名字
        inventoryFlow.setOperatorName(byId.getName());
        // 修改数量
        inventoryFlow.setChangeQuantity(inventoryInfo.getCurrentStock());
        // 库存ID
        inventoryFlow.setInventoryId(inventoryInfo.getInventoryId());
        Integer stockChange = inventoryInfo.getStockChange();
        if (stockChange>0){
            inventoryFlow.setOperationType("入库");
            // 操作原因
            inventoryFlow.setOperationReason(inventoryInfo.getReason());
            inventoryFlowService.getBaseMapper().insert(inventoryFlow);
        }else {
            inventoryFlow.setOperationType("出库");
            // 操作原因
            inventoryFlow.setOperationReason(inventoryInfo.getReason());
            inventoryFlowService.getBaseMapper().insert(inventoryFlow);
        }
    }

    // 根据 ID 删除库存信息（逻辑删除）
    @DeleteMapping("/delete/{id}")
    public Result<?> deleteInventoryInfo(@PathVariable Integer id) {
        boolean update = inventoryInfoService.removeById(id);
        if (update) {
            return Result.ok();
        } else {
            return Result.fail("删除库存信息失败");
        }
    }

    // 根据 ID 更新库存信息
    @PutMapping("/update")
    public Result<?> updateInventoryInfo(@RequestBody InventoryInfo inventoryInfo, HttpServletRequest request) {
        extracted1(inventoryInfo,request);
        boolean update = inventoryInfoService.updateById(inventoryInfo);
        if (update) {
            return Result.ok();
        } else {
            return Result.fail("更新库存信息失败");
        }
    }

    // 根据 ID 查询库存信息
    @GetMapping("/get/{id}")
    public Result<?> getInventoryInfo(@PathVariable Integer id) {
        InventoryInfo inventoryInfo = inventoryInfoService.getById(id);
        if (inventoryInfo != null) {
            return Result.ok(inventoryInfo);
        } else {
            return Result.fail("未找到该库存信息");
        }
    }

    // 分页查询库存信息
    @GetMapping("/page")
    public Result<?> pageQuery(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "10") Integer pageSize,
                               @RequestParam(required = false) Integer skuId) {
        Page<InventoryInfo> page = new Page<>(pageNum, pageSize);
        Page<InventoryInfo> resultPage = inventoryInfoService.pageQuery(page, skuId);
        return Result.ok(resultPage);
    }

}

